﻿// 开发者:micropu
// 公司:佛山远钧智慧科技有限公司

using Furion.Logging.Extensions;
using Furion.Schedule;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Admin.NET.Application.SysncService.PlatFormSync;

/// <summary>
/// 平台同步定时任务,主任务
/// </summary>
[SuppressSniffer]
public class PlatFormSyncJobMain : IJob 
{
    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        var OnlineVar = App.GetService<IPlatFormJobManager>();
        //Console.WriteLine($"平台同步定时任务--主任务{DateTime.Now}");

        // 检查是否有其他实例正在运行
        if (!OnlineVar.isRunning())
        {
            try
            {
                // 获取信号量
                await OnlineVar.semaphore().WaitAsync();

                // 设置标志表示方法正在运行
                OnlineVar.setRunning(true);

                // 实际逻辑
                try
                {
                    SqlSugarRepository<Device> _repApp_Device = new SqlSugarRepository<Device>();

                    var DevicesList = await _repApp_Device.AsQueryable()
                    .Includes(u => u.Project)
                    .Where(a =>  a.Project.Platform == PlatformType.fssj
                                 && a.Project.Status == StatusEnum.Enable
                                 && a.Status == StatusEnum.Enable
                                 && a.Project.IsDelete == false
                                 && a.IsDelete == false)
                    .ToListAsync();

                    foreach (var device in DevicesList)
                    {
                        // 检查 DevicesDic 中是否已经包含了该设备，避免重复添加
                        if (!string.IsNullOrEmpty(device.ClientSn) && !OnlineVar.PlatformOnlineDevicesDic().ContainsKey(device.ClientSn))
                        {
                            // 创建 PassDevice 对象并添加到 DevicesDic 中
                            PassDevice passDevice = new PassDevice
                            {
                                Device = device,
                                IsOnline = false, // 假设初始状态为离线
                                CancelToken = new CancellationTokenSource() // 创建 CancellationTokenSource
                            };
                            OnlineVar.PlatformOnlineDevicesDic().TryAdd(device.ClientSn, passDevice); // 尝试添加到 DevicesDic 中
                        }
                    }

                    // 查找 DevicesDic 存在但 DevicesList 中不存在的设备，将其移除
                    foreach (var device in OnlineVar.PlatformOnlineDevicesDic())
                    {
                        if (!DevicesList.Any(a => a.ClientSn == device.Key))
                        {
                            OnlineVar.RemoveDevice(device.Key);
                        }
                    }

                    // 创建设备连接住建任务
                    await CreateDeviceTask(DevicesList);
                }
                catch (Exception)
                {
                    // 处理异常，可以记录日志或者进行其他操作
                    // $"从数据库中添加设备时出错... {ex.Message}".LogInformation();
                }
            }
            finally
            {
                // 释放信号量并重置标志
                OnlineVar.setRunning(false);
                OnlineVar.semaphoreRelease();
            }
        }
        else
        {
            // 如果方法正在运行，则忽略当前调用
            // $"从数据库中添加设备已经有一个实例在运行...".LogInformation();
        }
    }

    // 动态创建设备连接住建任务
    public static async Task CreateDeviceTask(List<Device> DevicesList)
    {
        // 查找所有作业，包括 JobType == null 的非有效作业
        var _schedulerFactory = App.GetService<ISchedulerFactory>();
        var jobs = _schedulerFactory.GetJobs();

        // 查找 DevicesList 中存在但 jobs 中不存在的设备，将其添加
        var NotInJobList = DevicesList.Where(d => !jobs.Any(a => a.JobId == d.ClientSn)).ToList();

        foreach (var job in NotInJobList)
        {
            // 创建新的作业, 通过 ISchedulerFactory 创建
            // _schedulerFactory.AddJob<PlatFormSyncJob>(job.ClientSn, concurrent: false, Triggers.PeriodSeconds(10));

            var jobBuilder = JobBuilder.Create<PlatFormSyncJob>()
                .SetJobId(job.ClientSn)   // 作业 Id
                .SetJobType<PlatFormSyncJob>()    // 作业类型，支持多个重载
                .SetDescription($"住建同步")   // 作业描述
                .SetGroupName("ZjSync")
                .SetConcurrent(false);   // 并行还是串行方式，false 为 串行
                //.SetProperties(new Dictionary<string, object> { { "ProjectId", job.Project.Id } })
                //.SetProperties(new Dictionary<string, object> { { "Tenantld",  job.TenantId } })
                //.SetProperties(new Dictionary<string, object> { { "CreateOrgld", job.CreateOrgId } })
                //.SetProperties(new Dictionary<string, object> { { "CreateOrgName", job.CreateOrgName } });

            // 产生15-25的随机数
            Random random = new Random();
            int randomNumber = random.Next(15, 26); // upper bound is exclusive, so use 26
            _schedulerFactory.AddJob(jobBuilder, Triggers.PeriodSeconds(randomNumber));
           await Task.Delay(1000);
        }

        // 查找 jobs 中存在但 DevicesList 中不存在的设备，将其移除
        var NotInDeviceList = jobs.Where(d => !DevicesList.Any(a => a.ClientSn == d.JobId)).ToList();

        foreach (var job in NotInDeviceList)
        {
            // 删除作业
            if (job.JobId != "MainSync") _schedulerFactory.RemoveJob(job.JobId);
        }
    }
}
